<template>
    <div>
        <section class="todoapp">
            <!-- header -->
            <header class="header">
                <h1>todos</h1>
                <input
                    class="new-todo"
                    autofocus
                    autocomplete="off"
                    placeholder="What needs to be done?"
                    @keyup.enter="addTodo"
                >
            </header>

            <!-- section -->
            <section class="main">
                <input
                    class="toggle-all"
                    id="toggle-all"
                    type="checkbox"
                    @click="toggleAll(!allcheck)"
                    :checked="allcheck"
                >
                <label for="toggle-all"></label>
                <ul class="todo-list">
                    <TodoItem name="Todo" v-for="(todo,index) in filterTodo" :key="index" :todo="todo"/>
                </ul>
            </section>

            <!-- footer -->
            <footer class="footer">
                <span class="todo-count">
                <strong>{{number}}</strong>
                    {{number | nums('item')}} left
                </span>
                <ul class="filters">
                    <li v-for="(v,i) in filters" :key="i" @click="type = i">
                        <a>
                            {{i}}
                        </a>
                    </li>
                </ul>
                <button class="clear-completed" v-show="todos.length > number" @click="clearAll">
                    Clear completed
                </button>
            </footer>
        </section>
    </div>
</template>

<script>
import TodoItem from "./TodoItem";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      type: "all",
      filters: {
        all: todos => todos,
        active: todos => todos.filter(todos => !todos.done),
        complated: todos => todos.filter(todos => todos.done)
      }
    };
  },
  methods: {
    ...mapActions(["toggleAll", "clearAll"]),
    addTodo(e) {
      console.log(e.target.value);
      let text = e.target.value;
      if (text.trim()) {
        this.$store.dispatch("addTodo", text);
      }
    }
  },
  computed: {
    todos() {
      return this.$store.state.todos;
    },
    allcheck() {
      return this.todos.every(todo => todo.done);
    },
    number() {
      return this.$store.state.todos.filter(todo => !todo.done).length;
    },
    filterTodo() {
      return this.filters[this.type](this.todos);
    }
  },
  filters: {
    nums: (i, v) => (i > 1 ? v + "s" : v)
  },
  components: {
    TodoItem
  }
};
</script>
<style src="../css/main.css"></style>
<style scoped>
</style>